import urllib
import BeautifulSoup as bs

class Querier:
    def __init__(self):
        self.shortName = "discogs"
        self.longName = "Discogs.com"
        self.provides = ['album_front_large', 'album_front_small', 'artist_art_large', 'artist_art_small']

        self.searchReleaseURL = "http://www.discogs.com/search?type=releases&q="
        self.searchArtistURL = "http://www.discogs.com/search?type=artists&q="
        self.baseURL = "http://www.discogs.com"

    def process(self, item):
        artist = item.artist
        album = item.album

        query = self.searchReleaseURL + urllib.quote("%s %s" % (artist.encode("UTF-8"), album.encode("UTF-8")))

        data = urllib.urlopen (query).read()
        soup = bs.BeautifulSoup (data)
        m = soup("ol")
        try:
            entryPage=m[0]('li')[0]('a')[0]['href']
        except IndexError:
            return None
        return self.queryArt(entryPage)

    def queryArt(self, release):
        data = urllib.urlopen (self.baseURL+release).read ()
        soup = bs.BeautifulSoup (data)
        m = soup("td", {"valign":"top", "align":"center"})
        try:
            image = m[0]('a')[0]['href']
            small = m[0]('img')[0]['src']
        except:
            return None
        return self.queryImage(image, small)

    def queryImage(self, image, smallRelease):
        ret = []
        ret.append(smallRelease)

        data = urllib.urlopen (self.baseURL+image).read ()
        soup = bs.BeautifulSoup (data)
        m = soup("img", {"border":"0"})
        try:
            ret.append(m[1]['src'])
        except:
            return None


#       largeSize = xmms2covers.imgEngine.sizeOfImage(largeRelease)
#       smallSize = xmms2covers.imgEngine.sizeOfImage(smallRelease)

#       if largeSize[0] >= 300:
#           largeUseRelease = largeRelease
#       elif largeSize[0] <= 180 and largeSize[0] > smallSize[0]:
#           smallUseRelease = largeRelease

#       if smallUseRelease is None:
#           smallUseRelease = smallRelease
#       if largeUseRelease is None:
#           largeUseRelease = None

        return ret
